//
//  AddViewController.m
//  WWallet
//
//  Created by Aries on 11-9-23.
//  Copyright 2011年 bit. All rights reserved.
//

#import "AddViewController.h"
#import "IWExpenseItem.h"
#import "RegexKitLite.h"

@implementation AddViewController
@synthesize txtTitle;
@synthesize txtAmount;
@synthesize switchDirection;
@synthesize txtDateYear;
@synthesize txtDateMonth;
@synthesize txtDateDay;
@synthesize txtRemark;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [txtTitle release];
    [txtAmount release];
    [switchDirection release];
    [txtDateYear release];
    [txtDateMonth release];
    [txtDateDay release];
    [txtRemark release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(saveClicked)] autorelease];
    
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:@"yyyy"];
    
    self.txtDateYear.text = [dateFormatter stringFromDate:[NSDate date]];
    
    [dateFormatter setDateFormat:@"MM"];
    self.txtDateMonth.text = [dateFormatter stringFromDate:[NSDate date]];
    
    [dateFormatter setDateFormat:@"dd"];
    self.txtDateDay.text = [dateFormatter stringFromDate:[NSDate date]];
    
    [dateFormatter release];
}

- (void)saveClicked
{
    NSString *titleReg = @"^\\s+$";
    if([self.txtTitle.text length]==0 || [[self.txtTitle.text componentsMatchedByRegex:titleReg] count]==1){
        UIAlertView *alert = [UIAlertView alloc];
        [alert initWithTitle:@"稍等！" message:@"还没输入事项内容：）" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
        [alert autorelease];
        [alert show];
        return;
    }
    
    NSString *amountReg = @"^\\d+\\.{0,}\\d{0,}$";
    if([[self.txtAmount.text componentsMatchedByRegex:amountReg] count] != 1){
        UIAlertView *alert = [UIAlertView alloc];
        [alert initWithTitle:@"稍等！" message:@"金额输入有误：）" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
        [alert show];
        [alert release];
        return;
    }
    
    
    NSString *yearReg = @"^\\d{4}$", *monthReg=@"^\\d{1,2}$";
    if([self.txtDateYear.text length]!=4 || [[self.txtDateYear.text componentsMatchedByRegex:yearReg] count]!=1)
    {
        UIAlertView *alert = [UIAlertView alloc];
        [alert initWithTitle:@"稍等！" message:@"日期输入有误(年份)"  delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
        //[alert initWithTitle:self.txtDateYear.text message:[NSString stringWithFormat:@"%d",[[self.txtDateYear.text componentsMatchedByRegex:yearReg] count]]  delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
        [alert show];
        [alert release];
        return;
    }    
    if([self.txtDateMonth.text length]>2 || [[self.txtDateMonth.text componentsMatchedByRegex:monthReg] count]!=1 || [self.txtDateMonth.text intValue]<1 || [self.txtDateMonth.text intValue]>12)
    {
        UIAlertView *alert = [UIAlertView alloc];
        [alert initWithTitle:@"稍等！" message:@"日期输入有误(月份)"  delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
        [alert show];
        [alert release];
        return;
    }    NSRange range = [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    if([self.txtDateDay.text length]>2 || [[self.txtDateDay.text componentsMatchedByRegex:monthReg] count]!=1 || [self.txtDateDay.text intValue]<1 || [self.txtDateDay.text intValue]>range.length)
    {
        UIAlertView *alert = [UIAlertView alloc];
        [alert initWithTitle:@"稍等！" message:@"日期输入有误(天)"  delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
        [alert show];
        [alert release];
        return;
    }
    
    IWExpenseItem *item = [[IWExpenseItem alloc] init];
    
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    item.Title = txtTitle.text;
    item.Amount = [txtAmount.text floatValue];
    item.IsExpense = [switchDirection selectedSegmentIndex]==0?YES:NO;
    item.ExpenseTime = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@-%@-%@ 00:00:00",txtDateYear.text,txtDateMonth.text,txtDateDay.text]];    
    item.CreateTime = [NSDate date];
    item.Remark = txtRemark.text;
    
    [item save];
    /*
     */
    [dateFormatter release];
    [item release];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldReturn:(id)textField {    
    CGPoint p = self.view.center;
    
    if(textField==txtDateYear || textField==txtDateMonth || textField==txtDateDay)
        p.y += 32;
    if(textField==txtRemark)
        p.y += 64;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];
    self.view.center = p;
    [UIView commitAnimations];
    
    [textField resignFirstResponder];    
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(id)sender
{
    CGPoint p = self.view.center;
    
    if(sender==txtDateYear || sender==txtDateMonth || sender==txtDateDay)
        p.y -= 32;
    if(sender==txtRemark)
        p.y -= 64;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];
    self.view.center = p;
    [UIView commitAnimations];
    
    return YES;
}

- (void)viewDidUnload
{
    [self setTxtTitle:nil];
    [self setTxtAmount:nil];
    [self setSwitchDirection:nil];
    [self setTxtDateYear:nil];
    [self setTxtDateMonth:nil];
    [self setTxtDateDay:nil];
    [self setTxtRemark:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
